package selfview.sufutian.com.myapplication.draw2d;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.View;

public class CircleImage extends View {
    private Paint paint;
    private Bitmap bitmap;
    private int width, height, centerX, centerY, radius;

    public CircleImage(Context context) {
        this(context, null);
    }

    public CircleImage(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleImage(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        // 取得想要缩放的matrix參數


    }

    public void init(Bitmap bitmap) {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        this.bitmap = bitmap;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;

        centerX = width / 2;
        centerY = height / 2;

        radius = Math.min(width, height) / 2;

        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();



        Matrix matrix = new Matrix();
        matrix.postScale(width, height);
        if (bitmap != null) {
            Bitmap newbm = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, true);
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        /**
         * Canvas类中的saveLayer()方法，表示出创建一个图层入栈并返回该图层所在栈中的位置， 
         * 而restoreToCount()方法表示将指定栈中位置的图层绘制到canvas上面显示。 
         */
        int saveLayer = canvas.saveLayer(0, 0, width, height, paint, Canvas.ALL_SAVE_FLAG);
        // 画一个圆，也就是需要显示出来的圆  
        canvas.drawCircle(centerX, centerY, radius, paint);
        //设置位图模式为PorterDuff.Mode.SRC_IN  
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, 0, 0, paint);
        // 清空位图模式  
        paint.setXfermode(null);
        // 给圆形图片画一个3像素的边框  
        paint.setStrokeWidth(3);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.parseColor("#65f692"));
        canvas.drawCircle(centerX, centerY, radius, paint);

        canvas.restoreToCount(saveLayer);
    }
}  
